/**
 * 
 */
package com.epam.traning.taskmanager.content;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

import com.epam.traning.taskmanager.content.contract.TaskContract;
import com.epam.traning.taskmanager.db.DBHelper;

/**
 * @author IstiN
 *
 */
public class TasksProvider extends ContentProvider {

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#delete(android.net.Uri, java.lang.String, java.lang.String[])
	 */
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		// TODO Auto-generated method stub
		return 0;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#getType(android.net.Uri)
	 */
	@Override
	public String getType(Uri uri) {
		return TaskContract.TasksColumns.CONTENT_TYPE;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
	 */
	@Override
	public Uri insert(Uri uri, ContentValues values) {
		String jsonData = values.getAsString("data");
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(jsonData);
			long id = dbHelper.addTask(jsonObject);
			Uri taskUri = ContentUris.withAppendedId(
					TaskContract.TasksColumns.CONTENT_URI, id);
			getContext().getContentResolver().notifyChange(
					taskUri, null);
			return taskUri;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private DBHelper dbHelper;
	
	/* (non-Javadoc)
	 * @see android.content.ContentProvider#onCreate()
	 */
	@Override
	public boolean onCreate() {
		dbHelper = new DBHelper(getContext(), null);
		return true;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
	 */
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		Cursor tasks = dbHelper.getTasks();
		tasks.setNotificationUri(getContext().getContentResolver(), uri);
		return tasks;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[])
	 */
	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

}
